<template>
    <div class="dh_xgj_manage">

        <div class="d_x_m-list">

            <div class="add">
                <el-button @click="add" type="primary" class="mb5">添加</el-button>
                <span>
                    <el-badge :value="sumtotal" class="item" type="primary">
                        <span class="b00a">总提交数</span>
                    </el-badge>
                    <el-badge :value="daynum" class="item">
                        <span class="ff53">今日提交</span>
                    </el-badge>
                    <!-- <span class="f18 wh bcf6 mr20 br5 p2">{{sumtotal}}</span><span class="br5 f18 wh bc4a p2">今日：{{daynum}}</span></span> -->
                </span>
            </div>
            <div class="inquire">
                <el-form :model="staffquery" :inline="true" size="mini">

                    <el-form-item label="代理等级：">
                        <!-- <el-input v-model="staffquery.name" clearable placeholder="请输入查询的用户名"></el-input> -->
                        <el-select v-model="staffquery.level">
                            <!-- <el-option label="平台" :value="1"></el-option> -->
                            <el-option v-for="item in levelname" :key="item" :label="(item-1)+'级代理'" :value="item" v-show="item !== 1"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="用户名：">
                        <el-input v-model="staffquery.name" clearable placeholder="请输入查询的用户名"></el-input>
                    </el-form-item>

                    <!-- <el-form-item label="手机号：">
                        <el-input v-model="staffquery.phone" clearable placeholder="请输入查询的手机号"></el-input>
                    </el-form-item> -->

                    <el-form-item label="日期：">
                        <el-date-picker
                            v-model="staffquery.create_time"
                            type="daterange"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickerOptions"
                        ></el-date-picker>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="requestdata(2)">查 询</el-button>
                    </el-form-item>
                </el-form>
            </div>

             <el-table
                :data="hrtable"
                border
                stripe
                height="500"
                :cell-style="cellStyle"
                :header-cell-style="rowClass"
                style="width: 100%!important;">
                    <el-table-column
                        type="index"
                        label="序号"
                        width="80">
                    </el-table-column>
                    <el-table-column
                        prop="name"
                        label="用户名"
                        min-width="120">
                    </el-table-column>
                    <el-table-column
                        prop="password"
                        label="密码"
                        min-width="140">
                    </el-table-column>
                    <el-table-column
                        prop="realname"
                        label="姓名"
                        min-width="140">
                    </el-table-column>
                    <el-table-column
                        label="等级"
                        min-width="180">
                        <template slot-scope="scope">
                            <span v-if="scope.row.level === 1">总代理</span>
                            <span v-else>{{ scope.row.level-1 | changestate }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="上级"
                        min-width="180">
                        <template slot-scope="scope">
                            <span>{{ scope.row.top_id | filbusiness }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="phone"
                        label="手机"
                        min-width="180">
                    </el-table-column>
                    <el-table-column
                        label="下级员工"
                        min-width="180">
                        <template slot-scope="scope">
                            <el-badge :value="'总:'+1+' 今'+1" class="item-table">
                                <!-- <el-button size="small">评论</el-button> -->
                                <span @click="lookuser(scope.$index,scope.row)" class="cup">查看</span>
                            </el-badge>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="入职时间"
                        min-width="160">
                        <template slot-scope="scope">
                            <span>{{  scope.row.create_time*1000 | formatDate }} {{  scope.row.create_time*1000 | formatDateBehind }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        min-width="160">
                        <template slot-scope="scope">
                            <el-button
                                type="primary"
                                @click="amend(scope.$index, scope.row)"
                                size="small"
                            >修改</el-button>
                            <el-button
                                type="danger"
                                @click="remove(scope.$index, scope.row)"
                                size="small"
                            >删除</el-button>
                        </template>
                    </el-table-column>
            </el-table>

            <div class="dialog">

                <el-dialog title="修改员工信息" :visible.sync="dialogFormVisible" center :append-to-body='true' :lock-scroll="false" top="20vh" width="450px">
								
                    <p class="dxm-ltb-text tc red mb5">*默认值是原始信息，重写编写提交即可</p>

                    <el-form :model="revamp" ref="revamp" :rules="rules" label-width="80px">

                        <!-- <el-form-item label="用户名" prop="name">
                            <el-select v-model="revamp.arr" clearable placeholder="请输入用户名">
                                <el-option label="平台" :value="1"></el-option>
                                <el-option v-for="item in businessname" :key="item.id" :value="item.name+'('+item.level-1 + '级代理)'" v-show="item.level !== 1"></el-option>
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="用户名">
                            <el-input v-model="revamp.name" clearable placeholder="请输入用户名"></el-input>
                        </el-form-item>
                        <el-form-item label="登录密码">
                            <el-input v-model="revamp.password" clearable placeholder="请输入登录密码"></el-input>
                        </el-form-item>
                        <el-form-item label="姓名">
                            <el-input v-model="revamp.realname" clearable placeholder="请输入姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号">
                            <el-input v-model="revamp.phone" clearable placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="refer()">提交修改</el-button>
                            <el-button @click="cancelquery()">取消</el-button>
                        </el-form-item>

                    </el-form>
                    
                </el-dialog>

                <el-dialog title="添加代理" :visible.sync="adddialog" center :append-to-body='true' :lock-scroll="false" top="20vh" width="450px">
                                    
                    <!-- <p class="dxm-ltb-text tc red">*灰色是原信息，填好修改信息后点击确定，信息自动更新</p> -->
                    <el-form :model="forminline" ref="forminline" :rules="rules" label-width="80px">

                        <el-form-item label="用户名" prop="arr">
                            <el-select v-model="forminline.arr" clearable placeholder="请输入用户名">
                                <el-option 
                                    v-for="item in businessname" 
                                    :key="item.id" 
                                    :value="[item.id,item.level]" 
                                    :label="item.level === 1 ? '总代理' : item.name+'('+ (item.level-1) + '级代理)'"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商户名" prop="name">
                            <el-input v-model="forminline.name" clearable placeholder="请输入用户名"></el-input>
                        </el-form-item>
                        <el-form-item label="登录密码" prop="password">
                            <el-input v-model="forminline.password" clearable placeholder="请输入登录密码"></el-input>
                        </el-form-item>
                        <el-form-item label="姓名" prop="realname">
                            <el-input v-model="forminline.realname" clearable placeholder="请输入姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="forminline.phone" clearable placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitAss()">立即创建</el-button>
                            <el-button @click="resetForm()">取消</el-button>
                        </el-form-item>
                    </el-form>
                    <!-- <div class="dxm-ltb-message mt20 df" v-for="(item,key) in input" :key="key">
                        <span :class="item.class">{{item.name}}</span>
                        <el-input class="dxm-ltbm-price" v-model="item.value" max="220px" :placeholder="item.text" clearable></el-input>
                    </div>

                    <div class="dxm-ltb-confirm mt20 tc">
                        <el-button type="primary" @click="refer" class="dxm-ltb-c-btn wh">确定</el-button>
                    </div> -->
                    
                </el-dialog>

            </div>

        </div>

        <div class="d_j_mber-block">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[100, 200, 300, 400]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagecount">
            </el-pagination>
        </div>

    </div>
</template>

<script>
import axios from "../js/request.js";
import axjs from "../js/request.js"
import {formatDate} from "../js/time.js";
import {timetamp} from "../js/time.js";
import {timedata} from "../js/time.js";
var that
export default {
    components: {},
    data() {
        return {
            // 缓存中的账号密码
            login:{},
            sumtotal:1000,
            daynum: 0,
            adddialog: false,
            querydialog: false,
            // removedialog: false,
            businessname: null,
            levelname: null,
            staffquery: {
                level: "",
                name:"",
                // phone: "",
                create_time: ""
            },
            // 添加员工的动态绑定信息
            forminline: {
                level: 2,
                name: "",
                password: "",
                phone: "",
                realname: "",
                top_id: "",
                arr:""
            },
            // 弹出层的内容数组，样式默认值等
            revamp:{
                id: "",
                // level: 2,
                name: "",
                password: "",
                phone: "",
                realname: "",
                // top_id: "",
            },
            options: [{
                value: '1',
                label: '超级管理员'
            }, {
                value: '2',
                label: '普通用户'
            }],
            value: '2',
            // levlename: [
            //     {label:"超级管理",value: 1},
            //     {label:"商家",value: 2},
            //     {label:"代理",value: 3},
            // ],	
            //列表数组
            hrtable:[],
            dialogFormVisible: false,           //弹出层的状态
            currentPage: 1,						//分页的默认页数
            pageSize: 100,                       //单页条数
            pagecount: 0,						//总页数
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                }
            },
            rules:{
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入登录密码', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' }
                ],
                realname: [
                    { required: true, message: '请输入员工的真实姓名', trigger: 'blur' }
                ],
                arr:[
                    { required: true, message: '请选择上级代理', trigger: 'change' }
                ]
            }
        };
    },
    // 过滤器
    filters:{
        // 数组过滤成同意拒绝（函数带的形参需要对应装换值的关键字，否则未定义）
        changestate(id){
            if(id !== 0){
                var chnNumChar = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
                var chnUnitSection = ["", "万", "亿", "万亿", "亿亿"];
                var chnUnitChar = ["", "十", "百", "千"];
                var strIns = "", chnStr = "";
                var unitPos = 0;
                var zero = true;
                while (id > 0) {
                    var v = id % 10;
                    if (v === 0) {
                        if (!zero) {
                            zero = true;
                            chnStr = chnNumChar[v] + chnStr;
                        }
                    } else {
                        zero = false;
                        strIns = chnNumChar[v];
                        strIns += chnUnitChar[unitPos];
                        chnStr = strIns + chnStr;
                    }
                    unitPos++;
                    id = Math.floor(id / 10);
                }
                return chnStr+"级代理";
            }
        },
        // 商户代理名称
        filbusiness(id){
            if(that.businessname !== null){
                that.businessname.forEach(item=>{
                    id === item.id ? id = item.name : "";
                })
            }else{return}
            return id
        },
        formatDate(time){
			var date = new Date(time);
			return formatDate(date, 'yyyy-MM-dd');
		},
		formatDateBehind(time){
			var date = new Date(time);
			return formatDate(date, 'hh:mm:ss')
		}
    },
    // 组件注册
    computed: {},
    watch: {},
    // 方法管理
    methods: {
        // form表单自带函数
        onSubmit() {
            // console.log('submit!');
        },

        // 员工数据查询
        requestdata(num){
            let that = this;
            let data = {list_rows:this.pageSize,page:this.currentPage}
            if(this.staffquery.create_time !== "" && this.staffquery.create_time !== null){
                data.start_time = timetamp(String(this.staffquery.create_time[0]));//开始时间
                data.end_time = timedata(this.staffquery.create_time[1]);//结束时间))
            }
            data.name = this.staffquery.name;
            data.phone = this.staffquery.phone;
            data.level = this.staffquery.level;
            // console.log(this.staffquery.create_time !== "" && this.staffquery.create_time !== null)
            for(var i in data) data[i] === "" ? delete data[i] : "";
            // console.log(data)
            axjs.request("/aLiPayBusiness/list","post",JSON.stringify(data)).then(resp=>{
                // console.log(resp)
                if(num === 2 ){
                    resp.data.data.total
                    ? (that.$message({
                        message: "找到"+resp.data.data.total+"条数据",
                        type: "success"
                    })) 
                    : (this.$message.error("没有符合条件数据"));
                }
                that.pagecount = resp.data.data.total
                that.hrtable = resp.data.data.data
            })
        },

        add(){
            this.adddialog = true;
        },
        // 添加员工
        submitAss(){
            this.$refs.forminline.validate(valid=>{
                if(valid){
                    // console.log("456")
                    let that = this;
                    let daydate = parseInt((new Date()).getTime()/1000)
                    // console.log(daydate)
                    let data = {create_time:daydate};
                    for(var i in that.forminline) i !== "arr" ? data[i] = that.forminline[i] : "";
                    data.top_id = that.forminline.arr[0]
                    data.level = that.forminline.arr[1]+1
                    let updata = JSON.stringify(data)
                    // console.log(data)
                    let axios = require("axios")
                    axios({
                        method: 'post',
                        url: '/index.php/aLiPayBusiness/add',
                        headers: { 'Content-Type': 'application/json' },
                        data: updata
                    }).then( resp=> {
                        // console.log(resp)
                        if(resp.data.code === 200){
                            data.id = resp.data.data;
                            this.hrtable.length === this.pagecount ? that.hrtable.unshift(data) : "";
                            data.level > that.levelname[that.levelname.length] ? that.levelname.push(this.staffquery.level) : "";
                            this.businessname.unshift(data);
                            // console.log(data.level,that.levelname[that.levelname.length-1])
                            that.adddialog = false;
                            this.$refs.forminline.resetFields();
                            that.forminline[i] = "";
                            this.$message({
                                message: "添加成功",
                                type: "success"
                            })
                        }else{return}
                    }).catch(err=>{
                        // console.log(err,"123")
                        this.$message.error("用户名已存在，请重写输入")
                    })
                    // axjs.request("/aLiPayBusiness/add","post",JSON.stringify(data)).then(resp=>{
                    //     // console.log(resp)
                    //     if(resp.data.code === 200){
                    //         data.id = resp.data.data;
                    //         this.staffquery.level === data.level ? that.hrtable.unshift(data) : "";
                    //         data.level > that.levelname[that.levelname.length] ? that.levelname.push(this.staffquery.level) : "";
                    //         this.businessname.unshift(data);
                    //         // console.log(data.level,that.levelname[that.levelname.length-1])
                    //         that.adddialog = false;
                    //         this.$refs.forminline.resetFields();
                    //         that.forminline[i] = "";
                    //         this.$message({
                    //             message: "添加成功",
                    //             type: "success"
                    //         })
                    //     }else{return}
                    // }).catch(err => {
                    //     console.log(err+"123456")
                    // })
                }else{return}
            })
        },
        // 添加取消
        resetForm(){
            this.adddialog = false
        },

        // 删除
        remove(index,row){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axjs.request("/aLiPayBusiness/delete","post",JSON.stringify({id:row.id,})).then(resp=>{
                    // console.log(resp)
                    if(resp.data.code === 200){
                        this.hrtable.splice(index,1)
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        for(var i=0;i<this.businessname.length;i++){
                            if(this.businessname[i].id === row.id){
                                // console.log(i)
                                this.businessname.splice(i,1)
                            }else{return}
                        }
                    }else{return}
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        
        // 弹出层以及修改员工信息
        amend(index,row){
            for(var i in this.revamp) this.revamp[i] = row[i];
            this.revamp.index = index;
            this.dialogFormVisible = true
        },
        // 修改员工信息
        refer(){
            // const that = this;
            // console.log(this.revamp)
            let data = {};
            for(var i in this.revamp) i !== "index" && i !== "id" && this.revamp[i] !== "" ? data[i] = this.revamp[i] : "";
            if(JSON.stringify(data) !== "{}"){
                data.id = this.revamp.id;
                // console.log(data)
                axjs.request("/aLiPayBusiness/update","post",JSON.stringify(data)).then(resp=>{
                    // console.log(resp)
                    this.dialogFormVisible = false;
                    if(resp.data.code === 200){
                        let key = this.revamp.index;
                        for(var o in data) this.hrtable[key][o] = data[o];
                        this.$message({
                            message: "代理信息修改成功",
                            type: "success"
                        })
                    }else{return}
                })
            }else{
                this.$message.error("没有可以提交的修改数据")
            }
        },
        cancelquery(){
            that.dialogFormVisible = false;
        },

        // 查看下级员工
        lookuser(index,row){
            this.$router.push({ path: "/manage", query: { row: JSON.stringify(row) } });
        },

        //   表格居中
        cellStyle: function({ row, column, rowIndex, columnIndex }) {
            return "text-align:center;";
        },
        rowClass: function({ row, rowIndex }) {
            return "text-align:center;";
        },

        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.requestdata(1)
        },
        //分页的跳页函数
        handleCurrentChange(val) {
            this.currentPage = val;
            // console.log(`当前页: ${val}`);
            this.requestdata(1)
        },
    },
    // 全部的生命周期函数
    created() {
        axjs.request("/aLiPayBusiness/list","post",JSON.stringify({list_rows:9999999,page:1})).then(resp=>{
            this.businessname = resp.data.data.data;

            
            axjs.request("/aLiPayShop/list","post",JSON.stringify({list_rows:9999999,page:1})).then(resp=>{
                this.sumtotal = resp.data.data.total;
                var that = this;
                var date = new Date();
                let daytime = date .getFullYear()+"-"+(date .getMonth()+1)+"-"+date .getDate()+" 00:00:00"
                let numarr = [];
                // let objnum = {name:'',num:0,daynum:0}
                resp.data.data.data.forEach(item=>{
                    item.create_time > timetamp(daytime) ? that.daynum += 1 : "";
                })

                for(var l=0;l<that.businessname.length;l++){
                    let objnum = {name:'',num:0,daynum:0}

                    resp.data.data.data.forEach(item=>{
                        
                        if(that.businessname[l].name === item.name){
                            objnum.name = item.name;
                            item.create_time > timetamp(daytime) 
                            ?  (objnum.num+=1,objnum.daynum+=1)
                            : objnum.num+=1
                        }else{}
                    })
                    numarr.push(objnum)
                }

                console.log(numarr)
            })

            // this.businessname.sort()
            let data = []
            resp.data.data.data.forEach(item=>{
                data.push(item.level)
            })
            this.levelname = Array.from(new Set(data))
            this.levelname.sort()
            // console.log(this.levelname)
        })
    },
    mounted() {
        const that = this;
        that.login = JSON.parse(sessionStorage.getItem("dh_xgj_login"))
        that.requestdata(1)
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
}
</script>
<style scoped>
    .dh_xgj_manage{
        padding: 10px;
        background-color: #ffffff;
        border-radius: 5px;
    }
    .inquire{
        border-right: 1px solid #EBEEF5;
        border-top: 1px solid #EBEEF5;
        border-left: 1px solid #EBEEF5;
        padding: 10px;
    }
    .add{
        display: flex;
        justify-content: space-between;
    }
    .item {
        margin-top: 10px;
        margin-right: 50px;
    }
    .item-table{
        margin-top: 10px;
    }
    /* 分页 */
    .d_j_mber-block{
        border-right: 1px solid #EBEEF5;
        border-bottom: 1px solid #EBEEF5;
        border-left: 1px solid #EBEEF5;
    }
</style>